package com.example.telesys.controller;

import com.example.telesys.dto.RegistDTO;
import com.example.telesys.dto.UpdatePasswordDTO;
import com.example.telesys.pojo.*;
import com.example.telesys.service.CustomerService;
import com.example.telesys.service.UserService;
import com.example.telesys.utils.Convert2MD5;
import com.example.telesys.utils.JwtUtils;
import com.example.telesys.utils.SendMail;
import com.example.telesys.utils.UuidUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.logging.log4j.status.StatusData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户登录
     */
    @RequestMapping("/login")
    public Map login(@RequestBody(required = false) User user) {
        Map<String, Object> loginMap = new HashMap<>();
        ApiResponse apiResponse = new ApiResponse();
        String username = user.getUsername();
        User userSelect = userService.verifyUserByUsername(username);
        Boolean isExists = (userSelect != null) ? true : false;

        //如果用户名不存在
        if (!isExists) {
            apiResponse.setCode(StatusCode.NOT_FOUND);
            apiResponse.setMessage(StatusMessage.USER_NOT_FOUND);
            loginMap.put("apiResponse", apiResponse);
        } else {
            //经过加密后与数据库不匹配
            if (!Convert2MD5.getMD5(user.getPassword()).equals(userSelect.getPassword())) {
                apiResponse.setCode(StatusCode.FAILED);
                apiResponse.setMessage(StatusMessage.WRONG_LOGIN_INFO);
                loginMap.put("apiResponse", apiResponse);
            } else {
                //登录成功
                apiResponse.setCode(StatusCode.SUCCESS);
                apiResponse.setMessage(StatusMessage.SUCCESS);
                userSelect.setPassword(UuidUtil.getUuid());
                apiResponse.setData(userSelect);
                //更新token信息 更新用户信息

                String token = jwtUtils.generateToken(user.getUsername());
                loginMap.put("token", token);
                loginMap.put("apiResponse", apiResponse);

            }
        }
        return loginMap;
    }

    /**
     * 用户注册 注意 注册成功后需要添加客户信息
     */
    @RequestMapping("/regist")
    public ApiResponse regist(@RequestBody(required = false) RegistDTO registDTO) {
        ApiResponse apiResponse = new ApiResponse();
        //首先判断用户输入过来的验证码对不对
        String username = registDTO.getUsername();
        String verifyCodeFromUser = registDTO.getVerifycode();
        String verifyCodeFromRedis = (String) redisTemplate.opsForHash().get("code", username);
        if (!verifyCodeFromRedis.equals(verifyCodeFromUser)) {
            apiResponse.setCode(StatusCode.WRONG_VERIFY_CODE);
            apiResponse.setMessage(StatusMessage.WRONG_VERIFY_CODE);
            return apiResponse;
        }
        //接下来插入用户
        User user = new User();
        user.setUsername(registDTO.getUsername());
        user.setPassword(registDTO.getFirstpassword());
        user.setEmail(registDTO.getEmail());
        user.setRole(0);

        try {
            userService.regist(user);
            customerService.addCustomer(user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            apiResponse.setCode(StatusCode.FAILED);
            apiResponse.setMessage(StatusMessage.REGIST_FAILED);
            return apiResponse;
        }

        apiResponse.setCode(StatusCode.SUCCESS);
        apiResponse.setMessage(StatusMessage.REGIST_SUCCESS);
        return apiResponse;
    }


    /**
     * 判断用户注册时 输入的邮箱是否已被注册
     */
    @RequestMapping("/verifyUserByEmail")
    public ApiResponse verifyUserByEmail(@RequestParam("email") String email) {
        Boolean emailHasRegisted = userService.verifyUserByEmail(email);
        if (emailHasRegisted == true)
            return new ApiResponse(StatusCode.SUCCESS, StatusMessage.EMAIL_HAS_REGISTED, emailHasRegisted);
        return new ApiResponse(StatusCode.SUCCESS, StatusMessage.SUCCESS, emailHasRegisted);
    }

    /**
     * 首先生成将要发送给邮箱的验证码 然后保存在redis中
     * 等会注册按钮后 再从原位置中取
     */
    @RequestMapping("/getVerifyCode")
    public ApiResponse getVerifyCode(@RequestParam("email") String email, @RequestParam("username") String username) {
        SendMail sendMail = new SendMail();
        String data = UuidUtil.getUuid();
        redisTemplate.opsForHash().put("code", username, data);
        sendMail.sendMail(email, "恭喜您，账户验证成功！最新验证码为:" + data + "，若不是本人操作，请及时与网站管理员联系！@From.vincent.gitee.io");
        return new ApiResponse(StatusCode.SUCCESS, "尊敬的用户，您好！您的验证码信息已成功发送至邮箱，请注意查收！", "");
    }

    /**
     * 判断用户注册时 输入的用户名是否已被注册
     */
    @RequestMapping("/verifyUserByUsername")
    public ApiResponse verifyUserByUsername(@RequestParam("username") String username) {
        User user = userService.verifyUserByUsername(username);
        Boolean usernameHasRegisted = (user != null) ? true : false;
        if (usernameHasRegisted == true)
            return new ApiResponse(StatusCode.SUCCESS, StatusMessage.USERNAME_HAS_REGISTED, usernameHasRegisted);
        return new ApiResponse(StatusCode.SUCCESS, StatusMessage.SUCCESS, usernameHasRegisted);
    }


    /**
     * 用户更改密码
     */
    @RequestMapping("/updatePassword")
    public ApiResponse updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) {
        User user = new User();
        user.setUsername(updatePasswordDTO.getUsername());

        User selectUser = userService.verifyUserByUsername(user.getUsername());
        if (!Convert2MD5.getMD5(updatePasswordDTO.getOldpassword()).equals(selectUser.getPassword())) {
            return new ApiResponse(StatusCode.FAILED, StatusMessage.WRONG_OLD_PASSWORD, null);
        } else if (updatePasswordDTO.getOldpassword().equals(updatePasswordDTO.getFirstnewpassword())) {
            return new ApiResponse(StatusCode.FAILED, StatusMessage.DUPLICATE_PASSWORD, null);
        }
        user.setPassword(Convert2MD5.getMD5(updatePasswordDTO.getFirstnewpassword()));
        int updatePassword = userService.updatePassword(user);
        if (updatePassword == 0) {
            return new ApiResponse(StatusCode.FAILED, StatusMessage.FAILED, updatePassword);
        }
        return new ApiResponse(StatusCode.SUCCESS, StatusMessage.UPDATEPWD_SUCCESS, updatePassword);
    }


    /**
     * 用户重置密码
     */
    @RequestMapping("/userResetPassword")
    public ApiResponse userResetPassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) {
        User user = new User();
        user.setUsername(updatePasswordDTO.getUsername());
        user.setPassword(Convert2MD5.getMD5(updatePasswordDTO.getFirstnewpassword()));
        int userResetPassword = userService.updatePassword(user);
        if (userResetPassword == 0) {
            return new ApiResponse(StatusCode.FAILED, StatusMessage.RESETPWD_FAILED, userResetPassword);
        }
        return new ApiResponse(StatusCode.SUCCESS, StatusMessage.RESETPWD_SUCCESS, userResetPassword);
    }


    /**
     * 用户发送重置密码给邮箱
     */
    @RequestMapping("/sendMailForget")

    public ApiResponse sendMailForget(@RequestParam("email") String email) {
        User user = userService.selectUserByEmail(email);
        try {
            SendMail sendMail = new SendMail();
            String username = user.getUsername();
            String token = jwtUtils.generateToken(username);
            String path = "http://192.168.1.105:8080/#/resetPassword?username=" + username + "&token=" + token;
            String url = "<a href='" + path + "'>" + path + "</a>";
            String mailContent = "您好，您已经请求了重置密码！你可以点击链接来重置密码：" + url + " @From.vincent.gitee.io";
            sendMail.sendMail(email, mailContent);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse(StatusCode.FAILED, StatusMessage.SEND_RESETPWD_FAILED, "");
        }
        return new ApiResponse(StatusCode.SUCCESS, StatusMessage.SEND_RESETPWD_SUCCESS, "");
    }

    /**
     * 检查登录的角色 是否是管理员 如果不是 驳回登录操作
     */
    @RequestMapping("/checkLoginRole")
    public ApiResponse checkLoginRole(@RequestBody User user, ApiResponse apiResponse) {
        apiResponse.setCode(StatusCode.SUCCESS);
        apiResponse.setMessage(StatusMessage.SUCCESS);
        User selectUser = userService.verifyUserByUsername(user.getUsername());
        if (selectUser == null) {
            apiResponse.setCode(StatusCode.FAILED);
            apiResponse.setMessage(StatusMessage.FAILED);
            return apiResponse;
        } else {
            //如果是用户 则驳回登录操作
            if (selectUser.getRole() == 0) {
                apiResponse.setCode(StatusCode.LACK_OF_AUTHORITY);
                apiResponse.setMessage(StatusMessage.LACK_OF_AUTHORITY);
                return apiResponse;
            }
        }
        return new ApiResponse(StatusCode.SUCCESS, StatusMessage.SUCCESS, selectUser);
    }
}
